package com.lejin.usercenter.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lejin.usercenter.entity.UserSchool;
import com.lejin.usercenter.mapper.UserSchoolMapper;
import com.lejin.usercenter.service.IUserSchoolService;

import com.lejin.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 学校 服务实现类
 * </p>
 *
 * @author luminghua
 * @since 2022-04-21
 */
@Service
public class UserSchoolServiceImpl extends ServiceImpl<UserSchoolMapper, UserSchool> implements IUserSchoolService {


    @Autowired
    private UserSchoolMapper userSchoolMapper;
    @Override
    public ResultVO findUserSchoolByUid(String userId) {

        if (StringUtils.isEmpty(userId)){
            return new ResultVO(false,"用户Id不能为空");
        }


        UserSchool userSchool = new LambdaQueryChainWrapper<UserSchool>(userSchoolMapper).eq(UserSchool::getUserId, userId).one();
      return new ResultVO(true,"success",userSchool);
    }

    @Override
    public ResultVO addUserSchool(UserSchool userSchool) {


        if (StringUtils.isEmpty(userSchool.getUserId())){
            return new ResultVO(false,"用户ID不能为空");

        }


        //数据库是否有id

        UserSchool userSchool1 = new LambdaQueryChainWrapper<UserSchool>(userSchoolMapper).eq(UserSchool::getUserId, userSchool.getUserId()).one();

        if (StringUtils.isEmpty(JSONUtil.toJsonStr(userSchool1))){

            userSchoolMapper.insert(userSchool);
            return new ResultVO(true,"用户插入成功");
        }


        UpdateWrapper<UserSchool> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",userSchool.getUserId());

        int update = userSchoolMapper.update(userSchool, updateWrapper);

        if (update>0){
            return new ResultVO(true,"用户修改成功");
        }


        return new ResultVO(false,"用户添加失败");
    }
}
